package com.ezhan.install;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;

import static com.ezhan.logging.LogManager.log;
import static com.ezhan.message.NotifierManager.showError;
import static com.ezhan.message.NotifierManager.showSuccess;

public class PythonLibInstaller {
    public void executePythonLibInstallations(String installPythonLib,String pythonLib) {
        log("开始安装Python库...");

        File py_lib = new File(pythonLib);
        // 1. 检查文件夹是否存在
        if (!py_lib.isDirectory()) {
            log("错误: 未选择有效的Python库文件夹");
            showError("请选择包含Python库安装文件的文件夹");
            return;
        }

        // 2. 获取所有txt文件
        File[] commandFiles = py_lib.listFiles((dir, name) -> name.toLowerCase().endsWith(".txt"));

        if (commandFiles == null || commandFiles.length == 0) {
            log("错误: 未找到任何命令文件 (.txt)");
            showError("文件夹中未找到命令文件 (.txt)");
            return;
        }

        log("找到 " + commandFiles.length + " 个命令文件");

        // 3. 执行每个命令文件
        int successCount = 0;
        int totalCount = commandFiles.length;

        for (File commandFile : commandFiles) {
            if (executePythonLibCommand(commandFile, installPythonLib, py_lib)) {
                successCount++;
            }
        }

        // 4. 显示结果
        if (successCount == totalCount) {
            log("所有Python库安装完成!");
            showSuccess("Python库安装成功!");
        } else {
            log("部分Python库安装失败: " + successCount + "/" + totalCount);
            showError("部分Python库安装失败");
        }
    }

    private boolean executePythonLibCommand(File commandFile, String installPythonLib, File py_lib) {
        try {
            log("执行命令文件: " + commandFile.getName());

            // 1. 读取命令文件内容
            String command = readCommandFile(commandFile);
            if (command == null || command.trim().isEmpty()) {
                log("错误: 命令文件为空");
                return false;
            }

            log("执行命令: " + command);

            // 2. 执行命令
            //拆分命令字符串为单独参数，\s+表示匹配任意空白字符多次
            String[] commandParts = command.split("\\s+");


            // 构建命令列表
            ArrayList<String> cmdList = new ArrayList<>();
            cmdList.add("cmd");
            cmdList.add("/c");
            cmdList.add(installPythonLib); // Python 解释器路径
            cmdList.add("-m");
            Collections.addAll(cmdList, commandParts); // 添加其他参数

            ProcessBuilder builder = new ProcessBuilder(cmdList);
            builder.directory(py_lib); // 设置工作目录
            builder.redirectErrorStream(true); // 合并错误流
            Process process = builder.start();

            // 3. 读取输出
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    log(line);
                }
            }

            // 4. 等待执行完成
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                log("错误: 命令执行失败，退出代码: " + exitCode);
                return false;
            }

            log("命令执行成功: " + commandFile.getName());
            return true;
        } catch (Exception e) {
            log("执行命令错误: " + e.getMessage());
            return false;
        }
    }

    private String readCommandFile(File file) {
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            StringBuilder content = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
            return content.toString().trim();
        } catch (Exception e) {
            log("读取命令文件错误: " + e.getMessage());
            return null;
        }
    }

}
